<template>
  <section class="contian">
    <el-row type="flex" justify="space-between">
      <el-col :span="19">
        <h2 style="font-weight: normal; margin-bottom: 10px">发表新攻略</h2>
        <span style="font-size: 14px; color: #999999"
          >分享你的个人游记，让更多人看到哦</span
        >
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          class="demo-ruleForm"
        >
          <el-form-item prop="title">
            <el-input
              v-model="ruleForm.title"
              placeholder="请输入标题"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <client-only>
              <VueEditor :config="config" ref="vueEditor" />
            </client-only>
          </el-form-item>
          <el-form-item
            label="城市名称"
            prop="city"
            :rules="[
              { required: true, message: '请输入城市', trigger: 'blur' },
            ]"
            label-width="80px"
          >
            <el-autocomplete
              class="inline-input"
              v-model="ruleForm.city"
              :fetch-suggestions="querySearch"
              placeholder="请输入游玩城市"
              :trigger-on-focus="false"
              :debounce="0"
            ></el-autocomplete>
            <!-- <el-input
              v-model="ruleForm.city"
              placeholder="请输入城市"
            ></el-input> -->
          </el-form-item>
          <el-form-item
            class="sumbit"
            style="display: flex; align-items: center"
          >
            <el-button type="primary" @click="submitForm(ruleForm)"
              >发布</el-button
            >
            <span class="maybe"
              ><i class="font">或者</i>
              <el-link type="warning" @click="submitDraft(ruleForm)"
                >保存到草稿</el-link
              ></span
            >
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="4">
        <div class="draft">
          <p>草稿箱 ({{ caseArray.length }})</p>
          <div class="show" v-if="$store.state.user.userinfo.token">
            <div
              class="travels"
              v-for="(item, index) in caseArray"
              :key="index"
            >
              <h5 class="travels_title">{{ item.title }}</h5>
              <p class="edit">
                <span style="font-size: 14px">{{ systemTime }}</span>
                <em
                  ><i
                    class="el-icon-edit"
                    @click="edit(index)"
                    style="cursor: pointer"
                  ></i>
                  <i
                    class="el-icon-delete"
                    @click="del(index)"
                    style="cursor: pointer"
                  ></i
                ></em>
              </p>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </section>
</template>

<script>
export default {
  data() {
    return {
      restaurants: [],
      caseArray: [],
      systemTime: "",
      copyForm: {},
      ruleForm: {
        title: "",
        city: "",
        content: "",
      },
      config: {
        // 上传图片的配置
        uploadImage: {
          url: "http://157.122.54.189:9095/upload",
          name: "files",
          // res是结果，insert方法会把内容注入到编辑器中，res.data.url是资源地址
          uploadSuccess(res, insert) {
            console.log(res, insert);
            insert("http://157.122.54.189:9095" + res.data[0].url);
          },
          uploadError(err, insert) {
            console.dir(err, insert);
          },
        },

        // 上传视频的配置
        uploadVideo: {
          url: this.$axios.defaults.baseURL + "/upload",
          name: "file",
          uploadSuccess(res, insert) {
            console.log(res, insert);
            insert("http://localhost:3000" + res.data.url);
          },
        },
      },
      rules: {
        title: [{ required: true, message: "请输入标题", trigger: "blur" }],
      },
    };
  },
  methods: {
    //获取年月日
    addDate() {
      let nowDate = new Date();
      let date = {
        year: nowDate.getFullYear(),
        month: nowDate.getMonth() + 1,
        date: nowDate.getDate(),
      };
      this.systemTime = date.year + "-" + date.month + "-" + date.date;
    },
    //新增文章
    submitForm(data) {
      this.$store.commit("user/setURL", location.href);
      this.ruleForm.content = this.$refs.vueEditor.editor.root.innerHTML;
      this.$axios({
        url: "/posts",
        method: "post",
        data,
        headers: {
          Authorization:
            "Bearer " + this.$store.state.user.userinfo.token || "no token",
        },
      }).then((res) => {
        console.log(res);
        this.$router.push({ path: "/strategy" });
      });
    },
    //存草稿
    submitDraft(value) {
      if (this.$store.state.user.userinfo.token) {
        // this.copyForm = Object.assign({}, this.ruleForm);
        this.ruleForm.content = this.$refs.vueEditor.editor.root.innerHTML;
        console.log(value);
        this.copyForm = Object.assign({}, this.ruleForm); //深拷贝
        if (!this.copyForm.title) this.copyForm.title = "【无标题】";
        // console.log(this.copyForm);
        this.caseArray = Object.assign([], this.$store.state.user.drafts);
        this.caseArray.unshift(this.copyForm);
        this.$store.commit("user/setDrafts", this.caseArray);
        this.ruleForm = {
          title: "",
          city: "",
          content: "",
        };
        // this.caseArray = this.$store.state.user.drafts;
      } else {
        this.$store.commit("user/setURL", location.href);
        this.$message.error("请先登录");
        this.$router.push("/user/login");
      }
    },
    //编辑文章
    edit(index) {
      // console.log(this.caseArray[index]);
      this.ruleForm = { ...this.caseArray[index] };
      if (this.ruleForm.title == "【无标题】") {
        this.ruleForm.title = "";
      }
      this.$refs.vueEditor.editor.clipboard.dangerouslyPasteHTML(
        0,
        this.ruleForm.content
      );
      // this.copyForm = Object.assign({}, this.ruleForm); //深拷贝
    },
    del(index) {
      this.$confirm("确定删除嘛？", "提示", {
        distinguishCancelAndClose: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.caseArray = [...this.$store.state.user.drafts];
          this.caseArray.splice(index, 1);
          this.$store.commit("user/setDrafts", this.caseArray);
          this.$message({
            duration: 800,
            type: "info",
            message: "删除成功",
          });
        })
        .catch((action) => {});
    },
    querySearch(queryString, cb) {
      this.$axios({
        url: "/airs/city",
        params: { name: queryString },
      }).then((res) => {
        this.restaurants = res.data.data.map((v) => {
          return { value: v.name };
        });
        console.log(this.restaurants);
        cb(this.restaurants);
      });
    },
    //   this.$axios({
    //     url: "/airs/city",
    //     params: { name: queryString },
    //   }).then((res) => {
    //     this.restaurants = res.data.data;
    //     callback(this.restaurants);
    //   });
  },
  mounted() {
    this.$route.query.city
      ? (this.ruleForm.city = this.$route.query.city)
      : this.$route.query.city;
    this.addDate();
    setTimeout(() => {
      // this.caseArray = this.$store.state.user.drafts;
      this.caseArray = Object.assign([], this.$store.state.user.drafts); //深拷贝出来
      // this.copyForm = Object.assign({}, this.ruleForm); //深拷贝
    }, 1);
  },
  watch: {},
};
</script>

<style lang="less" scoped>
.contian {
  width: 1000px;
  margin: 15px auto;
}
/deep/ .ql-editor {
  height: 350px;
}
.draft {
  border: 1px solid #cccccc;
  padding: 10px;
  .travels {
    padding: 5px 0;
    &_title:hover {
      color: orange;
      cursor: pointer;
    }
    .edit {
      display: flex;
      justify-content: space-between;
    }
  }
}
/deep/ .is-required {
  margin-top: 10px;
}
/deep/.el-link--inner {
  display: inline;
}
</style>